package cn.com.fssg.platform.base.handler.impl.cl.xunlian;

import cn.com.fssg.platform.base.handler.TaskHandler;
import cn.com.fssg.platform.biz.BizUtil;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Component
public class ClXunlianTaskHandler implements TaskHandler {
//    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    private SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String APPLY_TYPE = "APPLY_XUNLIAN";

    @Override
    public boolean beforeSubmit(Task task) {
        return false;
    }

    @Override
    public boolean afterSubmit(Task oldTask, List<Task> newTasks) {
        boolean result = true;
        String proInstId;
        if (CollectionUtils.isEmpty(newTasks)) { //当前是最后一个节点
            proInstId = oldTask.getProcessInstanceId();

        } else {
            //选择下一个节点
            proInstId = newTasks.get(0).getProcessInstanceId();
        }
        //获取业务主表ID
        String querySql = String.format("select distinct(biz_key) from pxone.actex_hi_procinst where id = '%s'",proInstId);
        Map<String,Object> paramMap = new HashMap<>();
        Map<String, Object> map = jdbcTemplate.queryForMap(querySql, paramMap);
        //业务表主键
        String id = (String) map.get("biz_key");
        if (!ObjectUtils.isEmpty(id)) {
            String updateSql = "update cl_apply_xunlian set update_time = :updateTime where id = :id";
            paramMap.put("id", id);
            paramMap.put("updateTime", timeFormat.format(new Date()));
            jdbcTemplate.update(updateSql, paramMap);
            querySql = String.format("select * from cl_apply_xunlian where id = '%s'", id);
            map = jdbcTemplate.queryForMap(querySql, paramMap);
            insertHistory(map);
            createDyq(map);
        }
        return result;
    }

    /**
     * 计入历史申请
     * @param dataMap
     */
    private void insertHistory(Map<String, Object> dataMap) {
        if (!ObjectUtils.isEmpty(dataMap)) {
            //APPLY_XUNLIAN
            String sql = "insert into cl_apply_history (" +
                    "id, apply_time, jhr_idcard, apply_id," +
                    "shenpi_no, cjr_name, apply_type, " +
                    "create_by, create_time, update_by, update_time, " +
                    "finish, flow_status_describe, cjr_sex, cjr_birthday, " +
                    "cjr_minzu, cjr_hukou, cjr_idcard, has_cjr_card, " +
                    "cjr_num, cjr_type, cjr_type_name, cjr_cj_level, " +
                    "cjr_bx, cjr_jjqk, cjr_address, cjr_jhr, " +
                    "cjr_jhr_gx, cjr_jhr_phone, cjr_service_type, " +
                    "cjr_service_cat, apply_from, apply_user, " +
                    "submit_time, shenhe_time) values (" +
                    ":id, :apply_time, :jhr_idcard, :apply_id," +
                    ":shenpi_no, :cjr_name, :apply_type, " +
                    ":create_by, :create_time, :update_by, :update_time, " +
                    ":finish, :flow_status_describe, :cjr_sex, :cjr_birthday, " +
                    ":cjr_minzu, :cjr_hukou, :cjr_idcard, :has_cjr_card, " +
                    ":cjr_num, :cjr_type, :cjr_type_name, :cjr_cj_level, " +
                    ":cjr_bx, :cjr_jjqk, :cjr_address, :cjr_jhr, " +
                    ":cjr_jhr_gx, :cjr_jhr_phone, :cjr_service_type, " +
                    ":cjr_service_cat, :apply_from, :apply_user, " +
                    ":submit_time, :shenhe_time)";
            Map<String, Object> paraMap = new HashMap<>();
            paraMap.put("id", BizUtil.cur().getSnowflakeIdStr());
            paraMap.put("apply_time", dataMap.get("apply_time"));
            paraMap.put("jhr_idcard", dataMap.get("jhr_idcard"));
            paraMap.put("apply_id", dataMap.get("id"));
            paraMap.put("shenpi_no", dataMap.get("shenpi_no"));
            paraMap.put("cjr_name", dataMap.get("cjr_name"));
            paraMap.put("apply_type", APPLY_TYPE);
            paraMap.put("create_by", dataMap.get("create_by"));
            paraMap.put("create_time", dataMap.get("create_time"));
            paraMap.put("update_by", dataMap.get("update_by"));
            paraMap.put("update_time", dataMap.get("update_time"));
            paraMap.put("finish", dataMap.get("finish"));
            paraMap.put("flow_status_describe", dataMap.get("flow_status_describe"));
            paraMap.put("cjr_sex", dataMap.get("cjr_sex"));
            paraMap.put("cjr_birthday", dataMap.get("cjr_birthday"));
            paraMap.put("cjr_minzu", dataMap.get("cjr_minzu"));
            paraMap.put("cjr_hukou", dataMap.get("cjr_hukou"));
            paraMap.put("cjr_idcard", dataMap.get("cjr_idcard"));
            paraMap.put("has_cjr_card", dataMap.get("has_cjr_card"));
            paraMap.put("cjr_num", dataMap.get("cjr_num"));
            paraMap.put("cjr_type", dataMap.get("cjr_type"));
            paraMap.put("cjr_type_name", dataMap.get("cjr_type_name"));
            paraMap.put("cjr_cj_level", dataMap.get("cjr_cj_level"));
            paraMap.put("cjr_bx", dataMap.get("cjr_bx"));
            paraMap.put("cjr_jjqk", dataMap.get("cjr_jjqk"));
            paraMap.put("cjr_address", dataMap.get("cjr_address"));
            paraMap.put("cjr_jhr", dataMap.get("cjr_jhr"));
            paraMap.put("cjr_jhr_gx", dataMap.get("cjr_jhr_gx"));
            paraMap.put("cjr_jhr_phone", dataMap.get("cjr_jhr_phone"));
            paraMap.put("cjr_service_type", dataMap.get("cjr_service_type"));
            paraMap.put("cjr_service_cat", dataMap.get("cjr_service_cat"));
            paraMap.put("apply_from", dataMap.get("apply_from"));
            paraMap.put("apply_user", dataMap.get("apply_user"));
            paraMap.put("submit_time", dataMap.get("submit_time"));
            paraMap.put("shenhe_time", timeFormat.format(new Date()));
            jdbcTemplate.update(sql, paraMap);
        }
    }

    /**
     *
     * @param paramMap 康复训练申请参数
     */
    private void createDyq(Map<String, Object> paramMap){
        String monthString = monthFormat.format(new Date());
        String[] split = monthString.split("-");
        int currentYear = Integer.parseInt(split[0]);
        int currentMonth = Integer.parseInt(split[1]);

        if (currentMonth == 12) {
            currentMonth = 0;
            currentYear++;
        }
        String sql = "insert into cl_dyq (" +
                        "id, wt, bus_id, shenpi_no," +
                        "cjr_name, cjr_idcard, code, month, " +
                        "used_count, history_id, apply_type,max_count, " +
                        "shenpi_no_sub, cjr_hukou, cjr_service_type, cjr_service_cat," +
                        "dyq_money, invalid, invalid_time,cjr_sex," +
                        "cjr_birthday, cjr_type, cjr_cj_level, apply_time," +
                        "create_by, create_time, update_by, update_time," +
                        "del_flag) values(" +
                        "'%s', '%s', '%s', '%s', " +
                        "'%s', '%s', '%s', '%s'," +
                        " %s,  '%s', '%s',  %s," +
                        "'%s', '%s', '%s', '%s'," +
                        " %s, '%s', '%s', '%s'," +
                        "'%s', '%s', '%s', '%s'," +
                        "'%s', '%s', '%s', '%s'," +
                        "'%s')";
        int index = 1, maxCount = 20, year, usedCount = 0;
        String busId = (String) paramMap.get("id");
        String shenpiNo = (String) paramMap.get("shenpi_no");
        String invalid = "0", delFlag = "0", invalidMonth;
        String insertSql, month, code, shenpiNoSub;
        int nextmonth;
        String cjrName = (String) paramMap.get("cjr_name");
        String cjrIdcard = (String) paramMap.get("cjr_idcard");
        String cjrServiceType = (String) paramMap.get("cjr_service_type");
        String cjrServiceCat = (String) paramMap.get("cjr_service_cat");
        String cjrHukou = (String) paramMap.get("cjr_hukou");
        String cjrSex = (String) paramMap.get("cjr_sex");
        String cjrType = (String) paramMap.get("cjr_type");
        String cjrCjLevel = (String) paramMap.get("cjr_cj_level");
        Date cjrBirthday = (Date) paramMap.get("cjr_birthday");
        Date applyTime = (Date)paramMap.get("apply_time");
        String createBy = BizUtil.cur().curUserId();
        String updateBy = createBy;

        String createTime = timeFormat.format(new Date());
        String updateTime = timeFormat.format(new Date());
        Date invalidTime;
        int dyqMoney = cjrServiceType.equals("1")? 3000 : 2000;
        Map<String, Object> map = new HashMap<>();
        String historySql = "select * from cl_apply_history where apply_id = :applyId";
        map.put("applyId", busId);
        Map<String, Object> historyMap = jdbcTemplate.queryForMap(historySql, map);
        map.remove(("applyId"));
        for (int i = currentMonth; i < 12; i++) {
            nextmonth = i + 1;
            month = currentYear + "-" + nextmonth;
            year = nextmonth == 12 ? currentYear + 1 : currentYear;
            if (nextmonth == 12) {
                invalidMonth = "01";
            } else {
                invalidMonth = nextmonth <= 10? "0"+ (nextmonth + 1) : String.valueOf(nextmonth + 1);
            }

            try {
                //过期时间下个月1号0点
                invalidTime = timeFormat.parse(year + "-" + invalidMonth + "-" + "01 00:00:00");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            //生成代用券
            shenpiNoSub = shenpiNo + "_" + index;
            code = "DYQXL" + shenpiNoSub;
            insertSql = String.format(sql,
                    BizUtil.cur().getSnowflakeIdStr(), "0", busId, shenpiNo,
                    cjrName, cjrIdcard, code, month,
                    usedCount, ObjectUtils.isEmpty(historyMap)? null: historyMap.get("id"), APPLY_TYPE, maxCount,
                    shenpiNoSub, cjrHukou, cjrServiceType, cjrServiceCat,
                    dyqMoney, invalid, invalidTime, cjrSex,
                    cjrBirthday, cjrType, cjrCjLevel, applyTime,
                    createBy, createTime, updateBy, updateTime,
                    delFlag
                    );

            jdbcTemplate.update(insertSql, map);
            index++;
        }
    }
}
